﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.project.service.impl;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.entity.SystemUser;
import com.hh.bss.auth.service.SystemUserService;
import com.hh.bss.base.*;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.SystemConstant;
import com.hh.bss.common.cache.SystemDicCache;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.entity.CompanyAttachment;
import com.hh.bss.customer.service.CustomerService;
import com.hh.bss.oa.entity.OaEmailSend;
import com.hh.bss.project.dao.*;
import com.hh.bss.project.entity.*;
import com.hh.bss.project.service.*;
import com.hh.bss.project.vo.query.*;
import com.hh.bss.talent.entity.CvEducation;
import com.hh.bss.talent.entity.CvSalary;
import com.hh.bss.talent.entity.CvWork;
import com.hh.bss.talent.service.CvService;
import com.hh.bss.util.*;



import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


@Service
@Transactional
public class ContractJobCvRecomServiceImpl extends BaseBusinessService<ContractJobCvRecom,java.lang.Integer>  implements ContractJobCvRecomService<ContractJobCvRecom,java.lang.Integer>{

	private ContractJobCvRecomDao contractJobCvRecomDao;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setContractJobCvRecomDaoImpl(ContractJobCvRecomDao dao) {
		this.contractJobCvRecomDao = dao;
	}
	private ContractJobService contractJobService;
	private SearchProjectCvService searchProjectCvService;
	public void setSearchProjectCvServiceImpl(SearchProjectCvService service) {
		this.searchProjectCvService = service;
	}
	private CvService cvService;
	private CustomerService customerService;
	private SystemUserService systemUserService;
	private SystemUser oldContractJobCvRecom;
	public void setSystemUserServiceImpl(SystemUserService service) {
		this.systemUserService = service;
	}
	
	
	public void setContractJobServiceImpl(ContractJobService service) {
		this.contractJobService = service;
	}	
	public void setCustomerServiceImpl(CustomerService service) {
		this.customerService = service;
	}	
	public void setCvServiceImpl(CvService service) {
		this.cvService = service;
	}	
	
	public EntityDao getEntityDao() {
		return this.contractJobCvRecomDao;
	}
	
	@Transactional(readOnly=true)
	public Page findPage(ContractJobCvRecomQuery query) {
		return contractJobCvRecomDao.findPage(query);
	}
	public Page findJobRecomCvPage(ContractJobCvRecomQuery query){
		Page page=contractJobCvRecomDao.findJobRecomCvPage(query);
		List list = (List) page.getResult();
		//设置cc项目名
		Map m=null;
		for(int i=0;list!=null&&i<list.size();i++){
			m=(Map)list.get(i);			
			m.put("jobManager", getJobPartnerName((Integer)m.get("jobId"),ConstantDic.JOB_PARTNER_TYPE_MC));
			m.put("projectId",contractJobService.getJobProjectId((Integer)m.get("jobId")));
			//System.out.println(m.get("cvName")+":"+getJobPartnerName((Integer)m.get("jobId"),ConstantDic.JOB_PARTNER_TYPE_MC));
			if ((Integer)m.get("custId")!=null) {
				m.put("jobContacter", getCustContacterName((Integer)m.get("custId"),ConstantDic.CUSTOMER_CONTACTER_TYPE_JOB_CONTACTER));
				m.putAll(customerService.getSimpleCompanyInfo((Integer)m.get("custId")));
			}
		}
		return page;
		
		//return contractJobCvRecomDao.findJobRecomCvPage(query);
	}
	private String getJobPartnerName(Integer jobId,String type){
		String sqls = "select a.job_id,group_concat((b.name) separator ',') as jobManager from contract_job_partner a,system_user b where a.job_id=? and a.account=b.account and a.role=? group by a.job_id";
		List values = new ArrayList();
		values.add(jobId);
		values.add(type);
		String name=null;
		List l=contractJobCvRecomDao.getJdbcDao().getJdbcTemplate().queryForList(sqls, values.toArray());
		if (l!=null&&l.size()>0) {
			Map m=(Map)l.get(0);
			name=(String)m.get("jobManager");
		}
		return name;
	}
	private String getCustContacterName(Integer custId,String type){
		String sqls = "select group_concat((a0.cv_name) separator ',') as contacterName,a1.cust_id from cv a0,customer_contacter a1 where a1.cust_id=? and a1.role=? and a0.id=a1.cv_id group by a1.cust_id ";
		List values = new ArrayList();
		values.add(custId);
		values.add(type);
		String name=null;
		List l=contractJobCvRecomDao.getJdbcDao().getJdbcTemplate().queryForList(sqls, values.toArray());
		if (l!=null&&l.size()>0) {
			Map m=(Map)l.get(0);
			name=(String)m.get("contacterName");
		}
		return name;
	}
	public List findJobRecomCv(ContractJobCvRecomQuery query){
		return contractJobCvRecomDao.findJobRecomCv(query);
	}
	
	public List getContractJobCvRecomById(Integer id) {
		// TODO Auto-generated method stub
		return contractJobCvRecomDao.getContractJobCvRecomById(id);
	}
	
	
	public void autoGenFile(HttpServletRequest request,
			ContractJobCvRecom contractJobCvRecom) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		  SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");     
		 // MultipartFile multipartFile = multipartRequest.getFile("fileRes");
	       /**构建文件保存的web目录**/     
	       
	       //把公司id也加到目录里
	       String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+SystemConstant.JOBRECOMDIR+"/"+dateformat.format(new Date())+"/"+contractJobCvRecom.getCvId();      
	       /**得到文件保存目录的真实路径**/     
	       String fileRealPathDir = request.getSession().getServletContext().getRealPath(fileWebPathDir);     
	       /**根据真实路径创建目录**/     
	       File fileSaveDir = new File(fileRealPathDir);     
	       if(!fileSaveDir.exists()) {    
	           fileSaveDir.mkdirs();     
	       }   
	       /**页面控件的文件流**/     
	       //MultipartFile multipartFile = multipartRequest.getFile("fileRes");      			       			      			       
	       /**上传文件名称**/     
	       String gentFileName ="CV_"+contractJobCvRecom.getCvId()+".doc";
	         
	       
	      
	       // 文件类型   
	         
	       // 获取文件大小，以kB为单位   
	       long size = 0;   
//	       Double fSize =Math.round(size/1024.0*100)/100.0;   
//	       String fileSize = Double.toString(fSize)+"KB";
	       //if (fSize==0) fSize=new Double(1);
	       /**拼成完整的文件保存路径加文件**/     
	       String fileName = fileRealPathDir + File.separator   + gentFileName;  
	       
	       
	       
	       File file = new File(fileName);      
	          
	       try {
	    	  
	    	  // File doc=genRecomDoc(request,contractJobCvRecom.getId());
	    	   //if (doc!=null) contractJobCvRecom.setUploadDoc(fileWebPathDir+"/"+ gentFileName);
	           //multipartFile.transferTo(file);  //将文件写入到指定的目录   
	       } catch (IllegalStateException e) {     
	           e.printStackTrace();     
	       }   
	       
	       
//	       contractJobCvRecom.setAttachmentFile(fileWebPathDir+"/"+ uploadFileName);
	       //如果没有填文件名称，则以文件名处理
		
	}
	public void save(ContractJobCvRecom contractJobCvRecom) throws DataAccessException{
		//检查是否有推荐过
		
		Object[] os={contractJobCvRecom.getCvId(),contractJobCvRecom.getJobId()};
		List l=contractJobCvRecomDao.getHibernateTemplate().find("from ContractJobCvRecom t where t.cvId=? and t.jobId=?",os);
		if(l!=null&&l.size()>0) throw new RuntimeException("简历已经推荐过改职位，不能重复推荐");
		contractJobCvRecomDao.save(contractJobCvRecom);
		contractJobCvRecomDao.flush();
		contractJobCvRecom.setProjectCvStatus(SearchProjectCv.STATUS_RECOM);		
		this.updateRecomStatus(contractJobCvRecom);
	}
	
	public OaEmailSend getOaEmailSendByRecomId(Integer id) {
		OaEmailSend oaEmailSend=new OaEmailSend();
		
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		//
		sql.append(" select * from ( ");
		sql.append(" select  a.id,a.job_id jobId,a.cv_id cvId,a.recom_result recomResult,a.recom_risk recomRisk,a.doc_size docSize,a.export_template exportTemplate,a.export_doc exportDoc,a.upload_doc uploadDoc,a.is_smsnote isSmsnote,a.status,a.creator,a.create_dt createDt,a.modifier,a.modified_dt modifiedDt,a.summary,b.cv_name cvName,c.name jobName from  contract_job_cv_recom a,cv b,contract_job c where a.cv_id=b.id and a.job_id=c.id and a.id=? " );
		sql.append(" ) t ");
		values.add(id);
		
		
		List l= contractJobCvRecomDao.getJdbcDao().findByQuery(sql.toString(),values.toArray(), new MapObjectRowMapper());
		
		if (l!=null&&l.size()>0){
			Map m=(Map)l.get(0);
			oaEmailSend.setCvName((String)m.get("cvName"));
			oaEmailSend.setJobName((String)m.get("jobName"));
			oaEmailSend.setAttachment((String)m.get("uploadDoc"));
			oaEmailSend.setCallFrom(ConstantDic.EmailSourceType_CR);
			oaEmailSend.setCallId(id);
			oaEmailSend.setSubject("职位\""+(String)m.get("jobName")+"\"人选推荐\""+(String)m.get("cvName")+"\"");
			//recomResult
			//查询职位联系人姓名和邮箱
			
			List jobContacter=getJobContacter((Integer)m.get("jobId"));
			if (jobContacter!=null&&jobContacter.size()>0){
				
				Map mc=(Map)jobContacter.get(0);
				oaEmailSend.setReciever((String)mc.get("email"));
				oaEmailSend.setRecieverName((String)mc.get("cvName"));
			}
			
		}
		
			
		return oaEmailSend;
	}
	public List getJobContacter(Integer jobId) {
		
		
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		//
		sql.append(" select * from ( ");
		sql.append(" select d.cv_name cvName,d.cv_name_en cvNameEn,d.email from contract_job a,customer b,customer_contacter c ");
		sql.append(" left join  cv d on c.cv_id=d.id ");
		//sql.append(" left join (select cv_id,group_concat((nbr) separator ',') as email from cv_contact_detail where contact_type='").append(ConstantDic.ContactType_EMAIL).append("' group by cv_id) e on c.cv_id=e.cv_id ");
		sql.append(" where a.id=? and a.cust_id=b.id and c.cust_id=b.id and c.role='").append(ConstantDic.CUSTOMER_CONTACTER_TYPE_JOB_CONTACTER).append("'");		
		sql.append(" ) t ");
		values.add(jobId);
		
		return contractJobCvRecomDao.getJdbcDao().findByQuery(sql.toString(),values.toArray(), new MapObjectRowMapper());
	}
	
	public File genRecomDoc(HttpServletRequest request,OnlineUser onlineUser,ContractJobCvRecom pContractJobCvRecom) {
		// TODO Auto-generated method stub
		
		Map dataMap=new HashMap();
		ContractJobCvRecom contractJobCvRecom=new ContractJobCvRecom();
		
		if (pContractJobCvRecom==null) return null;
		ContractJobCvRecom tempContractJobCvRecom=(ContractJobCvRecom)contractJobCvRecomDao.getById(pContractJobCvRecom.getId());
		BeanUtils.copyProperties(contractJobCvRecom, tempContractJobCvRecom);
		if (contractJobCvRecom==null) return null;
		//ContractJob contractJob
		dataMap.put("contractJobCvRecom", contractJobCvRecom);
		contractJobCvRecom.setRecomResult(StringHelper.clearHTMLTag(contractJobCvRecom.getRecomResult()));
		contractJobCvRecom.setRecomRisk(StringHelper.clearHTMLTag(contractJobCvRecom.getRecomRisk()));
		contractJobCvRecom.setSummary(StringHelper.clearHTMLTag(contractJobCvRecom.getSummary()));
		
		ContractJob contractJob=(ContractJob)contractJobService.getById(contractJobCvRecom.getJobId());
		Map jobMap=new HashMap();
		
		if (contractJob!=null)  {
			jobMap.put("name", StringHelper.clearHTMLTag(contractJob.getName(),true));
			jobMap.put("workLocation", SystemDicCache.getCodeName("LOCATION", ObjectUtils.toString(contractJob.getWorkLocation())));
			dataMap.put("contractJob", jobMap);
		}
		
		
		//cv
		Map cvMap=cvService.getCvInfoById(contractJobCvRecom.getCvId());
		System.out.println("cvMap:"+cvMap);
		if (cvMap!=null)  {		
			
			cvMap.put("sex", ConstantDic.getConstantDicCategoryValue(ConstantDic.SEX_TYPE, ObjectUtils.toString(cvMap.get("sex"))));	
			cvMap.put("birthday",DateHelper.toString((Date)cvMap.get("birthday"), DateHelper.DEFAULT_SHORT_DATE_FORMAT));
			cvMap.put("currentAddress",SystemDicCache.getCodeName("LOCATION", ObjectUtils.toString(cvMap.get("currentAddress"))));
			//生成图片
			if (cvMap.get("logo")!=null){
				File file = new File(request.getSession().getServletContext().getRealPath((String)cvMap.get("logo")));
				if (file.exists()){
					String picBase64=StringHelper.base64Encode(FileHelper.getFileBytes(file));
					cvMap.put("logo", picBase64);
					//FileHelper.getFileBytes(file);
				}
			}
			dataMap.put("cvMap", cvMap);
		}
		
//		CvCertificate
//		CvEducation
//		CvSkill
//		CvTrainning
//		CvWork
		List cvCertificateList=this.getEntityDao().getHibernateTemplate().find(" from CvCertificate t where t.cvId=?  and t.isEng='0' order by t.beginD desc  ", contractJobCvRecom.getCvId());
		if (cvCertificateList!=null)  dataMap.put("cvCertificateList", cvCertificateList);
		else{
			cvCertificateList=new ArrayList();
			 dataMap.put("cvCertificateList", cvCertificateList);
		}
		
		List cvEducationList=this.getEntityDao().getHibernateTemplate().find(" from CvEducation t where t.cvId=?  and t.isEng='0' order by t.beginD desc  ", contractJobCvRecom.getCvId());
		if (cvEducationList!=null) {
			CvEducation cvEducation=null;
			for(int i=0;i<cvEducationList.size();i++){
				cvEducation=(CvEducation)cvEducationList.get(i);
				cvEducation.setDegree_str(SystemDicCache.getCodeName("DEGREE", ObjectUtils.toString(cvEducation.getDegree())));
			}
			 dataMap.put("cvEducationList", cvEducationList);
		}else{
			cvEducationList=new ArrayList();
			dataMap.put("cvEducationList", cvEducationList);
		}
		
		List cvSkillList=this.getEntityDao().getHibernateTemplate().find(" from CvSkill t where t.cvId=?   ", contractJobCvRecom.getCvId());
		
		if (cvSkillList!=null)  dataMap.put("cvSkillList", cvSkillList);
		else{
			cvSkillList=new ArrayList();
			dataMap.put("cvSkillList", cvSkillList);
		}
		
		
		List cvTrainningList=this.getEntityDao().getHibernateTemplate().find(" from CvTrainning t where t.cvId=?  and t.isEng='0' order by t.beginD desc  ", contractJobCvRecom.getCvId());
		if (cvTrainningList!=null)  dataMap.put("cvTrainningList", cvTrainningList);
		else{
			cvTrainningList=new ArrayList();
			dataMap.put("cvTrainningList", cvTrainningList);
		}
		
		//工作经验
		List cvWorkList=this.getEntityDao().getHibernateTemplate().find(" from CvWork t where t.cvId=?  and t.isEng='0' order by t.beginD desc ", contractJobCvRecom.getCvId());
		if (cvWorkList!=null)  {
			List tl=new ArrayList();
			for(int i=0;i<cvWorkList.size();i++){
				CvWork oneorin=(CvWork)cvWorkList.get(i);
				CvWork one=new CvWork();
				tl.add(one);
				BeanUtils.copyProperties(one, oneorin);
				one.setDutyDesc(StringHelper.clearHTMLTag(one.getDutyDesc()));
				one.setProductSize(StringHelper.clearHTMLTag(one.getProductSize()));
				one.setDutySize(StringHelper.clearHTMLTag(one.getDutySize()));
				one.setScore(StringHelper.clearHTMLTag(one.getScore()));
				one.setCompany(StringHelper.clearHTMLTag(one.getCompany(),true));
				one.setTitle(StringHelper.clearHTMLTag(one.getTitle(),true));
				one.setReportTitle(StringHelper.clearHTMLTag(one.getReportTitle(),true));
				one.setLeaveResult(StringHelper.clearHTMLTag(one.getLeaveResult(),true));
				
			}
			
			dataMap.put("cvWorkList", tl);		
		}else{
			cvWorkList=new ArrayList();
			dataMap.put("cvWorkList", cvWorkList);
		}
		
		List cvSalary=this.getEntityDao().getHibernateTemplate().find(" from CvSalary t where t.cvId=?  ", contractJobCvRecom.getCvId());
		if (cvSalary!=null&&cvSalary.size()>0)  {
			CvSalary one=(CvSalary)cvSalary.get(0);
			CvSalary oneCvSalary=new CvSalary(); 
			BeanUtils.copyProperties(oneCvSalary,one);
			oneCvSalary.setBonusList(StringHelper.clearHTMLTag(oneCvSalary.getBonusList(),true));
			oneCvSalary.setExpectSalaryStr(SystemDicCache.getCodeName("SALARY",ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryStr(SystemDicCache.getCodeName("SALARY",ObjectUtils.toString(oneCvSalary.getCurrentSalary())));
			
			oneCvSalary.setExpectSalaryStr(SystemDicCache.getCodeName("SALARY",ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryStr(SystemDicCache.getCodeName("SALARY",ObjectUtils.toString(oneCvSalary.getCurrentSalary())));
			dataMap.put("cvSalary", oneCvSalary);		
		}else{			
			dataMap.put("cvSalary",new CvSalary());
		}
		
		//发送人信息
		SystemUser systemUser=null;
		if (onlineUser!=null) {
			systemUser=systemUserService.findByUsername(onlineUser.getUsername());
			if (systemUser!=null){
				dataMap.put("systemUser", systemUser);
			}
			
		}
		
		
		//开始生成
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		//configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "");
		configuration.setClassForTemplateLoading(this.getClass(), "/template");
		configuration.setClassicCompatible(true);
		//
		
		Template t=null;
		try {			
			
			StringBuffer str=FileHelper.read(this.getClass().getResource("/template/chrecom.ftl").getPath(),"UTF-8");
			String templateText= str.toString().replaceAll("<!---", "").replaceAll("--->", "");
			
			StringTemplateLoader stringTemplateLoader=new StringTemplateLoader();
			stringTemplateLoader.putTemplate("template", templateText);
			//test.ftl为要装载的模板
			configuration.setTemplateLoader(stringTemplateLoader);
			t = configuration.getTemplate("template");
			
			//configuration.s
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//输出文档路径及名称
		 SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");  
		 String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+SystemConstant.JOBRECOMDIR+"/"+dateformat.format(new Date())+"/"+contractJobCvRecom.getCvId();      
         /**得到文件保存目录的真实路径**/     
         String fileRealPathDir = request.getSession().getServletContext().getRealPath(fileWebPathDir);     
         /**根据真实路径创建目录**/     
         File fileSaveDir = new File(fileRealPathDir);
         //fileSaveDir.i
         if(!fileSaveDir.exists()) {    
            fileSaveDir.mkdirs();     
         }   
		//String fileName="CV_"+contractJobCvRecom.getCvId()+".doc";
         String cvName=(String)cvMap.get("cvName");
         String jobName=contractJob.getName();
         
         //String fileName= cvName+"_"+jobName+"_"+DateHelper.toString(new Date(), "yyyyMMdd")+".doc";
         String fileName= RandomStringUtil.getString(8)+"_CN.doc";
		pContractJobCvRecom.setUploadDoc(fileWebPathDir+"/"+ fileName);
		File outFile = new File(request.getSession().getServletContext().getRealPath(fileWebPathDir+"/"+fileName));
		
		Writer out = null;
		try {
			
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
        try {
        	//System.out.println(t.toString());
        	
			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			
			e.printStackTrace();
			return null;
		}finally{
			if (out!=null)
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		
		
		return outFile;
	}

	
	public void saveFile(MultipartHttpServletRequest multipartRequest,
			MultipartFile multipartFile, ContractJobCvRecom contractJobCvRecom,int type) {
		// TODO Auto-generated method stub
		 SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");     
		  
		//把公司id也加到目录里
	       String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+SystemConstant.JOBRECOMDIR+"/"+dateformat.format(new Date())+"/"+contractJobCvRecom.getCvId();      
	       /**得到文件保存目录的真实路径**/     
	       String fileRealPathDir = multipartRequest.getSession().getServletContext().getRealPath(fileWebPathDir);     
	       /**根据真实路径创建目录**/     
	       File fileSaveDir = new File(fileRealPathDir);     
	       if(!fileSaveDir.exists()) {    
	           fileSaveDir.mkdirs();     
	       }   
	       /**页面控件的文件流**/     
	       //MultipartFile multipartFile = multipartRequest.getFile("fileRes");      			       			      			       
	       /**上传文件名称**/     
	       String uploadFileName = multipartFile.getOriginalFilename();//    
	         
	       
	       /**获取文件的后缀**/     
	       String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);     
	       String preName = multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().indexOf("."));
	       // 文件类型   
	         
	       // 获取文件大小，以kB为单位   
	       long size = multipartFile.getSize();   
	       Double fSize =Math.round(size/1024.0*100)/100.0;   
	       String fileSize = Double.toString(fSize)+"KB";
	       if (fSize==0) fSize=new Double(1);
	       /**拼成完整的文件保存路径加文件**/     
	       //重新命名
	       if(!StringHelper.isEmpty(suffix))uploadFileName=RandomStringUtil.getString(8)+"."+suffix;
	       else uploadFileName=RandomStringUtil.getString(8);
	       
	       String fileName = fileRealPathDir + File.separator   + uploadFileName;     
	       
	       File file = new File(fileName);      
	          
	       try {     
	           multipartFile.transferTo(file);  //将文件写入到指定的目录   
	       } catch (IllegalStateException e) {     
	           e.printStackTrace();     
	       } catch (IOException e) {            
	           e.printStackTrace();     
	       }    
	       //multipartFile.g
	       if (type==1)
	               contractJobCvRecom.setUploadDoc(fileWebPathDir+"/"+ uploadFileName);
	       if (type==2)
		           contractJobCvRecom.setUploadDocEn(fileWebPathDir+"/"+ uploadFileName);
	        
	       //contractJobCvRecom.setAttachmentFile(fileWebPathDir+"/"+ uploadFileName);
	       //如果没有填文件名称，则以文件名处理
		
	}

	
	public File genRecomDocEn(HttpServletRequest request,
			OnlineUser onlineUser, ContractJobCvRecom pContractJobCvRecom) {
		// TODO Auto-generated method stub
		Map dataMap=new HashMap();
        
		//ContractJob contractJob
        ContractJobCvRecom contractJobCvRecom=new ContractJobCvRecom();
		
		if (pContractJobCvRecom==null) return null;
		ContractJobCvRecom tempContractJobCvRecom=(ContractJobCvRecom)contractJobCvRecomDao.getById(pContractJobCvRecom.getId());
		BeanUtils.copyProperties(contractJobCvRecom, tempContractJobCvRecom);
		
		
		
		dataMap.put("contractJobCvRecom", contractJobCvRecom);
		contractJobCvRecom.setRecomResult(StringHelper.clearHTMLTag(contractJobCvRecom.getRecomResult()));
		contractJobCvRecom.setRecomRisk(StringHelper.clearHTMLTag(contractJobCvRecom.getRecomRisk()));
		contractJobCvRecom.setSummary(StringHelper.clearHTMLTag(contractJobCvRecom.getSummary()));
		
		ContractJob contractJob=(ContractJob)contractJobService.getById(contractJobCvRecom.getJobId());
		Map jobMap=new HashMap();
		
		if (contractJob!=null)  {
			jobMap.put("name", StringHelper.clearHTMLTag(contractJob.getName(),true));
			jobMap.put("workLocation", SystemDicCache.getCodeNameEn("LOCATION", ObjectUtils.toString(contractJob.getWorkLocation())));
			dataMap.put("contractJob", jobMap);
		}
		
		
		//cv
		Map cvMap=cvService.getCvInfoById(contractJobCvRecom.getCvId());
		if (cvMap!=null)  {		
			
			cvMap.put("sex", ConstantDic.getConstantDicCategoryValueEn(ConstantDic.SEX_TYPE, ObjectUtils.toString(cvMap.get("sex"))));
			cvMap.put("married", cvMap.get("marriedEn"));
			cvMap.put("birthday",DateHelper.toString((Date)cvMap.get("birthday"), DateHelper.DEFAULT_SHORT_DATE_FORMAT));
			cvMap.put("currentAddress",SystemDicCache.getCodeNameEn("LOCATION", ObjectUtils.toString(cvMap.get("currentAddress"))));
			//生成图片
			if (cvMap.get("logo")!=null){
				File file = new File(request.getSession().getServletContext().getRealPath((String)cvMap.get("logo")));
				if (file.exists()){
					String picBase64=StringHelper.base64Encode(FileHelper.getFileBytes(file));
					cvMap.put("logo", picBase64);
					//FileHelper.getFileBytes(file);
				}
			}
			dataMap.put("cvMap", cvMap);
		}
		
//		CvCertificate
//		CvEducation
//		CvSkill
//		CvTrainning
//		CvWork
		List cvCertificateList=this.getEntityDao().getHibernateTemplate().find(" from CvCertificate t where t.cvId=?  and t.isEng='1' order by t.beginD desc   ", contractJobCvRecom.getCvId());
		if (cvCertificateList!=null)  dataMap.put("cvCertificateList", cvCertificateList);
		else{
			cvCertificateList=new ArrayList();
			 dataMap.put("cvCertificateList", cvCertificateList);
		}
		
		List cvEducationList=this.getEntityDao().getHibernateTemplate().find(" from CvEducation t where t.cvId=?  and t.isEng='1' order by t.beginD desc  ", contractJobCvRecom.getCvId());
		if (cvEducationList!=null) {
			CvEducation cvEducation=null;
			for(int i=0;i<cvEducationList.size();i++){
				cvEducation=(CvEducation)cvEducationList.get(i);
				cvEducation.setDegree_str(SystemDicCache.getCodeNameEn("DEGREE", ObjectUtils.toString(cvEducation.getDegree())));
			}
			 dataMap.put("cvEducationList", cvEducationList);
		}else{
			cvEducationList=new ArrayList();
			dataMap.put("cvEducationList", cvEducationList);
		}
		
		List cvSkillList=this.getEntityDao().getHibernateTemplate().find(" from CvSkill t where t.cvId=?   ", contractJobCvRecom.getCvId());
		
		if (cvSkillList!=null)  dataMap.put("cvSkillList", cvSkillList);
		else{
			cvSkillList=new ArrayList();
			dataMap.put("cvSkillList", cvSkillList);
		}
		
		
		List cvTrainningList=this.getEntityDao().getHibernateTemplate().find(" from CvTrainning t where t.cvId=?  and t.isEng='1' order by t.beginD desc   ", contractJobCvRecom.getCvId());
		if (cvTrainningList!=null)  dataMap.put("cvTrainningList", cvTrainningList);
		else{
			cvTrainningList=new ArrayList();
			dataMap.put("cvTrainningList", cvTrainningList);
		}
		
		//工作经验
		List cvWorkList=this.getEntityDao().getHibernateTemplate().find(" from CvWork t where t.cvId=?  and t.isEng='1'   order by t.beginD desc ", contractJobCvRecom.getCvId());
		if (cvWorkList!=null)  {
			List tl=new ArrayList();
			for(int i=0;i<cvWorkList.size();i++){
				CvWork oneorin=(CvWork)cvWorkList.get(i);
				CvWork one=new CvWork();
				tl.add(one);
				BeanUtils.copyProperties(one, oneorin);
				one.setDutyDesc(StringHelper.clearHTMLTag(one.getDutyDesc()));
				one.setProductSize(StringHelper.clearHTMLTag(one.getProductSize()));
				one.setDutySize(StringHelper.clearHTMLTag(one.getDutySize()));
				one.setScore(StringHelper.clearHTMLTag(one.getScore()));
				one.setCompany(StringHelper.clearHTMLTag(one.getCompany(),true));
				one.setTitle(StringHelper.clearHTMLTag(one.getTitle(),true));
				one.setReportTitle(StringHelper.clearHTMLTag(one.getReportTitle(),true));
				one.setLeaveResult(StringHelper.clearHTMLTag(one.getLeaveResult(),true));
			}
			dataMap.put("cvWorkList", tl);		
		}else{
			cvWorkList=new ArrayList();
			dataMap.put("cvWorkList", cvWorkList);
		}
		
		List cvSalary=this.getEntityDao().getHibernateTemplate().find(" from CvSalary t where t.cvId=?  ", contractJobCvRecom.getCvId());
		if (cvSalary!=null&&cvSalary.size()>0)  {			
			CvSalary one=(CvSalary)cvSalary.get(0);
			CvSalary oneCvSalary=new CvSalary(); 
			BeanUtils.copyProperties(oneCvSalary,one);
			oneCvSalary.setBonusList(StringHelper.clearHTMLTag(oneCvSalary.getBonusList(),true));
			oneCvSalary.setExpectSalaryStr(SystemDicCache.getCodeName("SALARY",ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryStr(SystemDicCache.getCodeName("SALARY",ObjectUtils.toString(oneCvSalary.getCurrentSalary())));
			
			oneCvSalary.setExpectSalaryEnStr(SystemDicCache.getCodeNameEn("SALARY",ObjectUtils.toString(oneCvSalary.getExpectSalary())));
			oneCvSalary.setCurrentSalaryEnStr(SystemDicCache.getCodeNameEn("SALARY",ObjectUtils.toString(oneCvSalary.getCurrentSalary())));
			dataMap.put("cvSalary", oneCvSalary);		
		}else{			
			dataMap.put("cvSalary",new CvSalary());
		}
		
		//发送人信息
		SystemUser systemUser=null;
		if (onlineUser!=null) {
			systemUser=systemUserService.findByUsername(onlineUser.getUsername());
			if (systemUser!=null){
				dataMap.put("systemUser", systemUser);
			}
			
		}
		
		
		//开始生成
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		//configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "");
		configuration.setClassForTemplateLoading(this.getClass(), "/template");
		configuration.setClassicCompatible(true);
		//
		
		Template t=null;
		try {			
			
			StringBuffer str=FileHelper.read(this.getClass().getResource("/template/enrecom.ftl").getPath(),"UTF-8");
			String templateText= str.toString().replaceAll("<!---", "").replaceAll("--->", "");
			
			StringTemplateLoader stringTemplateLoader=new StringTemplateLoader();
			stringTemplateLoader.putTemplate("template", templateText);
			//test.ftl为要装载的模板
			configuration.setTemplateLoader(stringTemplateLoader);
			t = configuration.getTemplate("template");
			
			//configuration.s
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//输出文档路径及名称
		 SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");  
		 String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+SystemConstant.JOBRECOMDIR+"/"+dateformat.format(new Date())+"/"+contractJobCvRecom.getCvId();      
         /**得到文件保存目录的真实路径**/     
         String fileRealPathDir = request.getSession().getServletContext().getRealPath(fileWebPathDir);     
         /**根据真实路径创建目录**/     
         File fileSaveDir = new File(fileRealPathDir);
         //fileSaveDir.i
         if(!fileSaveDir.exists()) {    
            fileSaveDir.mkdirs();     
         }   
		//String fileName="CV_EN_"+contractJobCvRecom.getCvId()+".doc";
         String cvName=(String)cvMap.get("cvName");
         String jobName=contractJob.getName();         
        // String fileName= cvName+"_"+jobName+"_"+DateHelper.toString(new Date(), "yyyyMMdd")+"(英).doc";
         String fileName= RandomStringUtil.getString(8)+"_EN.doc";
        pContractJobCvRecom.setUploadDocEn(fileWebPathDir+"/"+ fileName);
		File outFile = new File(request.getSession().getServletContext().getRealPath(fileWebPathDir+"/"+fileName));
		
		Writer out = null;
		try {
			
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
        try {
        	//System.out.println(t.toString());
        	
			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			
			e.printStackTrace();
			return null;
		}finally{
			if (out!=null)
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		
		
		return outFile;
	}

	
	public void updateRecomStatus(ContractJobCvRecom contractJobCvRecom) {
		// TODO Auto-generated method stub
		//查询职位项目
		
		ContractJobCvRecom oldContractJobCvRecom=(ContractJobCvRecom)contractJobCvRecomDao.getById(contractJobCvRecom.getId());
		List values=new ArrayList();
		values.add(oldContractJobCvRecom.getJobId());
		//暂时和ProjectCvStatus通用统一的字典
		oldContractJobCvRecom.setStatus(oldContractJobCvRecom.getProjectCvStatus());
		//values.add(contractJobCvRecom.getCvId());
		List l=contractJobCvRecomDao.getHibernateTemplate().find("from ContractJobSearchProject t where t.jobId=? ", values.toArray());
		ContractJobSearchProject contractJobSearchProject=null;
		SearchProjectCv searchProjectCv=null;
		for (int i=0;l!=null&&i<l.size();i++){
			contractJobSearchProject=(ContractJobSearchProject)l.get(i);
			searchProjectCv=new SearchProjectCv();
			searchProjectCv.setProjectId(contractJobSearchProject.getProjectId());
			searchProjectCv.setCvId(oldContractJobCvRecom.getCvId());
			searchProjectCv.setStatus(contractJobCvRecom.getProjectCvStatus());
			
			searchProjectCvService.updateProjectCvStatus(searchProjectCv);
		}
		//更新ContractJobCvRecom推荐人选的状态
		contractJobCvRecomDao.flush();
		//状态只能往前更新
		if (oldContractJobCvRecom.getStatus()==null) oldContractJobCvRecom.setStatus(contractJobCvRecom.getStatus());
		if (contractJobCvRecom.getStatus()==null) return;
		//状态只能递增
		//if (oldContractJobCvRecom.getStatus().intValue()>contractJobCvRecom.getStatus().intValue()) return;
		oldContractJobCvRecom.setStatus(contractJobCvRecom.getStatus());
		searchProjectCvService.update(oldContractJobCvRecom);
		contractJobCvRecomDao.flush();
		
		//searchProjectCvService.update(entity);
	}


	
	public ContractJobCvRecom getContractJobCvRecom(Integer jobId, Integer cvId) {
		// TODO Auto-generated method stub
		List values=new ArrayList();
		values.add(jobId);
		values.add(cvId);
		ContractJobCvRecom contractJobCvRecom=null;
		List l=contractJobCvRecomDao.getHibernateTemplate().find("from ContractJobCvRecom t where t.jobId=? and t.cvId=? ", values.toArray());
		if (l!=null&&l.size()>0) {
			contractJobCvRecom=(ContractJobCvRecom)l.get(0);
		}
		return contractJobCvRecom;
	}	
	
}
